<template>
  <div class="users_container">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入用户姓名"
            v-model="param.query"
            clearable
          >
            <el-button
              slot="append"
              @click="getUserList"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeUserState(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUserInfo(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <el-tooltip content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="param.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="param.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 添加用户弹出框 -->
      <el-dialog
        title="添加用户"
        @close="resetForm"
        :visible.sync="dialogVisible"
        width="50%"
      >
        <el-form
          :model="userForm"
          :rules="userFormRules"
          ref="userForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="userForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="userForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户信息 -->
      <el-dialog
        title="修改用户信息"
        :visible.sync="changeDialog"
        width="50%"
        @close="resetChangeForm"
      >
        <el-form
          :model="changeUserForm"
          :rules="changeUserFormRules"
          ref="changeUserForm"
          label-width="100px"
        >
          <el-form-item label="用户名">
            <el-input v-model="changeUserForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="changeUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="changeUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="changeDialog = false">取 消</el-button>
          <el-button type="primary" @click="putEditInfo">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  created() {
    this.getUserList();
  },
  data() {
    // 自定义数据规则
    var checkEmail = (rule, value, callback) => {
      let emailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (emailReg.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的邮箱"));
    };
    var checkMobile = (rule, value, callback) => {
      let mobileReg =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]18[0-9]|14[57])[0-9]{8}$/;
      if (mobileReg.test(value)) {
        return callback();
      }
      callback(new Error("请输入正确的手机号"));
    };
    return {
      // 请求参数
      param: { query: "", pagenum: 1, pagesize: 2 },
      // 用户信息
      userList: [],
      total: 0,
      pageNum: 1,
      dialogVisible: false,
      changeDialog: false,
      userForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      userFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      changeUserForm: {
        username: "",
        email: "",
        mobile: "",
        userId: "",
      },
      changeUserFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    async getUserList() {
      let { data: res } = await this.$http.get("/users", {
        params: this.param,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("你他妈的获取用户信息失败拉！");
      }
      this.total = res.data.total;
      this.pageNum = res.data.pagenum;
      this.userList = res.data.users;
    },
    // 修改用户信息并提交到数据库中
    async putUserInfo(userInfo) {
      let { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      } else {
        this.$message.success(res.meta.msg);
      }
    },
    handleSizeChange(newsize) {
      this.param.pagesize = newsize;
      this.getUserList();
    },
    handleCurrentChange(newpage) {
      this.param.pagenum = newpage;
      this.getUserList();
    },
    changeUserState(userInfo) {
      this.putUserInfo(userInfo);
    },
    resetForm() {
      this.$refs.userForm.resetFields();
    },
    addUser() {
      this.$refs.userForm.validate(async (valid) => {
        if (!valid) return;
        let { data: res } = await this.$http.post("/users", this.userForm);
        if (res.meta.status !== 201) return this.$message.error("添加用户失败");
        this.$message.success("添加用户成功！");
        this.getUserList();
        this.dialogVisible = false;
      });
    },
    // 修改用户信息
    changeUserData() {
      this.changeDialog = false;
    },
    resetChangeForm() {
      this.$refs.changeUserForm.resetFields();
    },
    editUserInfo(info) {
      this.changeDialog = true;
      this.changeUserForm.username = info.username;
      this.changeUserForm.email = info.email;
      this.changeUserForm.mobile = info.mobile;
      this.changeUserForm.userId = info.id;
    },
    putEditInfo() {
      this.$refs.changeUserForm.validate(async (valid) => {
        if (!valid) return;
        let { data: res } = await this.$http.put(
          "/users/" + this.changeUserForm.userId,
          {
            email: this.changeUserForm.email,
            mobile: this.changeUserForm.mobile,
          }
        );
        console.log(res);
        if (res.meta.status !== 200)
          return this.$message.error("修改用户信息失败");
        this.getUserList();
        this.$message.success("更改用户信息成功！");
        this.changeDialog = false;
      });
    },
    async deleteUser(infoId) {
      let result = await this.$confirm(
        "此操作将删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then((data) => {
          return data;
        })
        .catch((err) => {
          this.$message({
            type: "info",
            message: "已取消操作",
          });
          return err;
        });
      if (result == "cancel") return;
      let { data: res } = await this.$http.delete("users/" + infoId);
      if (res.meta.status !== 200) return this.$message.error("删除用户失败");
      this.getUserList();
      this.$message.success("删除用户成功！");
    },
  },
};
</script>

<style>
</style>